import { defineStore } from "pinia";
import { ref, watch } from 'vue'
import useMessage from "@/utils/useMessage.ts";
import {
    categoryBatchDelete,
    categoryBatchUpdate,
    categoryCreate,
    categoryDelete,
    categoryList,
    categoryUpdate
} from "@/services/api/category.ts";
import { useOrgStore } from "@/store/modules/organization";
import {hasPermission} from "@/utils/permission.ts";
import {Modal} from "ant-design-vue";
import {getCategoryTree} from "@/utils/treeDataFormat.ts";

export const useCategoryStore = defineStore('category', () => {
    const dataSource = ref<Category[]>([])
    const loading = ref(false)
    const searchValue = ref<string>('')
    const data = ref<Category[]>([])
    const orgStore = useOrgStore()

    // 根据名称[name]搜索分类
    const onSearch = () => {
        const term = searchValue.value.trim().toLowerCase()
        if (!term) {
            data.value = getCategoryTree(dataSource.value)
        }else {
            const result = dataSource.value.filter(item => item.name.toLowerCase().includes(term))
            data.value = getCategoryTree( result)
        }
    }
    // 根据类型[type]搜索分类
    const getCategories = (type?: CategoryType) => {
        if (!type) {
            data.value = getCategoryTree(dataSource.value)
        }else {
            const result = dataSource.value.filter(item => item.type.toLowerCase()=== type)
            data.value = getCategoryTree(result)
        }
        return data.value
    }

    const getList = async (force?: boolean) => {
        if (!force && dataSource.value.length > 0) {
            return
        }
        try {
            loading.value = true
            const res = await categoryList()
            if (res.code === 200) {
                dataSource.value = res.data || []
            } else {
                useMessage(res.code, res.message || '获取分类列表失败')
            }
        } catch (e: any) {
            useMessage(500, e.message || '请求失败，请重试或是联系我们')
        } finally {
            loading.value = false
        }
    }

    // 监听组织机构id变化，如果改变重新请求
    watch(() => orgStore.id, async () => {await getList(true)}, { immediate: true })

    const create = async (form:CategoryForm) => {
        if(!hasPermission('admin:category:create')) return false
        try {
            const res = await categoryCreate(form)
            useMessage(res.code, res.message)
            
            if (res.code === 200) {
                await getList(true)
                return true
            }
            return false
        } catch (e: any) {
            useMessage(500, e.message || '创建分类失败')
            return false
        }
    }

    const update = async (form: CategoryForm) => {
        if (!hasPermission('admin:category:update')) return false
        if (!form.id) {
            useMessage(500, '请选择要修改的分类')
            return false
        }

        try {
            const res = await categoryUpdate(form.id, form)
            useMessage(res.code, res.message)
            
            if (res.code === 200) {
                const item = dataSource.value.find(item => item.id ===form.id)
                if (item) {
                    Object.assign(item, form)
                }
                return true
            }
            return false
        } catch (e: any) {
            useMessage(500, e.message || '更新分类失败')
            return false
        }
    }
    const batchUpdate = async (id: Key[], form: object) => {
        if (!hasPermission('admin:category:update')) return false
        try {
            const res = await categoryBatchUpdate(id as number[], form)
            useMessage(res.code, res.message)
            if (res.code === 200) {
                for (const item of dataSource.value) {
                    if (id.includes(item.id)) {
                        Object.assign(item, form)
                    }
                }
            }
        }catch (e: any) {
            useMessage(500, e.message || '更新分类失败')
            return false
        }
    }

    const remove = async (id: number) => {
        if (!hasPermission('admin:category:delete')) return false
        try {
            Modal.confirm({
                title: '删除确认',
                content: '确定要删除此分类吗？此操作不可逆，请谨慎操作！',
                onOk: async () => {
                    const res = await categoryDelete(id)
                    useMessage(res.code, res.message)
                    if (res.code === 200) {
                        dataSource.value = dataSource.value.filter(item => item.id !== id)
                    }
                }
            })
        } catch (e: any) {
            useMessage(500, e.message || '删除分类失败')
        }
    }
    const batchRemove = async (id: Key[]) => {
        if (!hasPermission('admin:category:delete')) return false
        try {
            Modal.confirm({
                title: '删除确认',
                content: '确定要删除选中的分类吗？此操作不可逆，请谨慎操作！',
                onOk: async () => {
                    const res = await categoryBatchDelete(id as number[])
                    useMessage(res.code, res.message)
                    if (res.code === 200) {
                        dataSource.value = dataSource.value.filter(item => !id.includes(item.id))
                    }
                }
            })
        } catch (e: any) {
            useMessage(500, e.message || '删除分类失败')
        }
    }

    return {
        dataSource,
        loading,
        searchValue,
        data,
        getList,
        create,
        update,
        remove,
        getCategories,
        onSearch,
        batchUpdate,
        batchRemove
    }
}, { persist:{ pick: ['dataSource']}})